using System.Collections.Generic;
using UnityEngine;

namespace Gj
{
    public class ToastHelper : NodeHelper
    {
        public GameObject item;
        private float _lastTime;
        private List<ToastItemHelper> _nodes;
        private List<ToastItemHelper> _tmps;

        protected override BindDataType bindDataType => BindDataType.Float;

        private void Awake()
        {
            _nodes = new List<ToastItemHelper>();
            _tmps = new List<ToastItemHelper>();
        }

        private void Update()
        {
            if (_nodes.Count == 0) return;
            for (var i = 0; i < _nodes.Count; i++)
                if (!_nodes[i].show)
                {
                    DestroyItem(_nodes[i]);
                    _nodes.RemoveAt(i);
                    break;
                }
        }

        protected override void BindData(float f)
        {
            if (f > _lastTime)
            {
                _lastTime = f;
                var node = GetItem();
                node.SetData(_data);
                _nodes.Add(node);
                node.Show();
            }
        }

        private ToastItemHelper GetItem()
        {
            if (_tmps.Count > 0)
            {
                var item = _tmps[0];
                _tmps.RemoveAt(0);
                return item;
            }

            return Instantiate(item, gameObject.transform).GetComponent<ToastItemHelper>();
        }

        private void DestroyItem(ToastItemHelper itemHelper)
        {
            _tmps.Add(itemHelper);
        }
    }
}